package com.easylinkin.linkappapi.safe.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.safe.dao.DangerousDictMapper;
import com.easylinkin.linkappapi.safe.dto.DangerousDictDto;
import com.easylinkin.linkappapi.safe.entity.DangerousDict;
import com.easylinkin.linkappapi.safe.entity.vo.DangerousDictVo;
import com.easylinkin.linkappapi.safe.service.DangerousDictService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * DangerousDict表服务实现类
 *
 * @author zhengwen
 * @date 2022/08/15
 */
@Slf4j
@Service("appDangerousDictService")
public class DangerousDictServiceImpl extends ServiceImpl
        <DangerousDictMapper, DangerousDict> implements DangerousDictService {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Override
    public boolean saveOne(DangerousDict appDangerousDict) {
        commonService.setCreateAndModifyInfo(appDangerousDict);
        // appDangerousDict.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validParamRequired(appDangerousDict);
        validRepeat(appDangerousDict);
        validParamFormat(appDangerousDict);
        return save(appDangerousDict);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(DangerousDict appDangerousDict) {
        Assert.notNull(appDangerousDict.getId(), "id不能为空");
        commonService.setModifyInfo(appDangerousDict);
        //appDangerousDict.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(appDangerousDict);
        validParamFormat(appDangerousDict);
        return updateById(appDangerousDict);
    }

    @Override
    public IPage<DangerousDict> selectPage(Page page, DangerousDict appDangerousDict) {
        //appDangerousDict.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, appDangerousDict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(DangerousDict appDangerousDict, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<DangerousDict> page = selectPage(new Page(0, -1), appDangerousDict);
        List<DangerousDict> records = page.getRecords();
        List
                <DangerousDictVo> appDangerousDictVos = new ArrayList<>();
        for (DangerousDict expert : records) {
            appDangerousDictVos.add(new DangerousDictVo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "DangerousDict导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, appDangerousDictVos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public IPage<DangerousDictDto> getDataByParam(Page page, DangerousDict appDangerousDict) {
        return baseMapper.getDataByParam(page, appDangerousDict);
    }

    @Override
    public DangerousDict getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(DangerousDict appDangerousDict) {
        /* QueryWrapper<DangerousDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", appDangerousDict.getName());
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<DangerousDict> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("名称有重复");
        }
        if (ObjectUtils.isEmpty(appDangerousDict.getId())) {
            throw new BusinessException("名称已存在");
        }
        if (!appDangerousDict.getId().equals(list.get(0).getId())) {
            throw new BusinessException("名称已存在");
        }
                    */

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(DangerousDict appDangerousDict) {
        //Assert.notNull(appDangerousDict, "参数为空");
        //Assert.isTrue(StringUtils.isNotBlank(appDangerousDict.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(DangerousDict appDangerousDict) {
        //Assert.isTrue(appDangerousDict.getName() == null || appDangerousDict.getName().length() <= 50,
        //        "名称超长");
    }
}

